package com.dexilaonian.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import com.dexilaonian.R;
import com.dexilaonian.activity.LoginActivity;
import com.dexilaonian.adpter.AllOrderAdapter;
import com.dexilaonian.bean.AllorderBean;
import com.dexilaonian.ui.BaseFragment;
import com.dexilaonian.utils.Constant;
import com.dexilaonian.utils.JsonUtil;
import com.dexilaonian.utils.Okhttp;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * Created by Administrator on 2018/3/27.
 */

public class OverFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {

    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.refreshLayout)
    SwipeRefreshLayout refreshLayout;
    private List<AllorderBean> allorderBeanList = new ArrayList<>();
    private AllOrderAdapter allOrdeAdapter;
    private Handler mHandler = new Handler(Looper.getMainLooper());
    private GridLayoutManager mLayoutManager;
    private final int PAGE_COUNT = 6;
    private int lastVisibleItem = 0;
    private boolean mIsRefreshing = false;

    @Override
    protected void initData(Bundle savedInstanceState) {
    }

    @Override
    protected void initView(View layoutView) {
    }

    @Override
    public int getLayoutID() {
        return R.layout.fragment_allorder;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        recyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (mIsRefreshing) {
                    return true;
                } else {
                    return false;
                }
            }
        });
        initRefreshLayout();
        initGetAll(6);
        return rootView;
    }

    private void initRefreshLayout() {
        refreshLayout.setColorSchemeResources(android.R.color.holo_blue_light, android.R.color.holo_red_light,
                android.R.color.holo_orange_light, android.R.color.holo_green_light);
        refreshLayout.setOnRefreshListener(this);
    }

    private void initGetAll(int pager) {
        String allOrder_url = Constant.base_url + "/user/getOrders.do";
        Map<String, String> map = new HashMap<>();
        map.put("type", 2 + "");
        map.put("index", 2 + "");
        map.put("pageSize", pager+ "");
        Okhttp.postString(true, allOrder_url, map, new Okhttp.CallBac() {
            @Override
            public void onError(Call call, Exception e, String state, int id) {
            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    int status = Integer.parseInt(jsonObject.optString("status"));
                    if (status == 16 || status == 34) {
                        startActivity(new Intent(getActivity(), LoginActivity.class));
                    } else if (status == 0) {
                        String data = jsonObject.optString("data");
                        JSONObject object = new JSONObject(data);
                        String items = object.optString("items");
                        ArrayList<AllorderBean> allorderBeen = JsonUtil.json2beans(items, AllorderBean.class);
                        allorderBeanList.clear();
                        allorderBeanList.addAll(allorderBeen);
                        allOrdeAdapter = new AllOrderAdapter(allorderBeanList, getActivity(), allorderBeanList.size() > 0 ? true : false);
                        mLayoutManager = new GridLayoutManager(getActivity(), 1);
                        recyclerView.setLayoutManager(mLayoutManager);
                        //recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
                        recyclerView.setAdapter(allOrdeAdapter);
                        recyclerView.setItemAnimator(new DefaultItemAnimator());
                        allOrdeAdapter.notifyDataSetChanged();
                        initRecyclerView();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onNoNetwork(String state) {
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onRefresh() {
        mIsRefreshing = true;
        refreshLayout.setRefreshing(true);
        allOrdeAdapter.resetDatas();
        initGetAll(6);
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                refreshLayout.setRefreshing(false);
                mIsRefreshing = false;
            }
        }, 1000);
    }

    private void initRecyclerView() {
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    if (allOrdeAdapter.isFadeTips() == false && lastVisibleItem + 1 == allOrdeAdapter.getItemCount()) {
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                update(allOrdeAdapter.getRealLastPosition());

                            }
                        }, 500);
                    }
                    if (allOrdeAdapter.isFadeTips() == true && lastVisibleItem + 2 == allOrdeAdapter.getItemCount()) {
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                update(allOrdeAdapter.getRealLastPosition());
                            }
                        }, 500);
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = mLayoutManager.findLastVisibleItemPosition();
            }
        });
    }

    private List<AllorderBean> getDatas(final int firstIndex, final int lastIndex) {
        List<AllorderBean> resList = new ArrayList<>();
        for (int i = firstIndex; i < lastIndex; i++) {
            if (i < allorderBeanList.size()) {
                resList.add(allorderBeanList.get(i));
            }
        }
        return resList;
    }

    private void update(int pager) {
        String allOrder_url = Constant.base_url + "/user/getOrders.do";
        Map<String, String> map = new HashMap<>();
        map.put("type", 0 + "");
        map.put("index", 1 + "");
        map.put("pageSize", pager + "");
        Okhttp.postString(true, allOrder_url, map, new Okhttp.CallBac() {
            @Override
            public void onError(Call call, Exception e, String state, int id) {
            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    int status = Integer.parseInt(jsonObject.optString("status"));
                    if (status == 16 || status == 34) {
                        startActivity(new Intent(getActivity(), LoginActivity.class));
                    } else if (status == 0) {
                        String data = jsonObject.optString("data");
                        JSONObject object = new JSONObject(data);
                        String items = object.optString("items");
                        ArrayList<AllorderBean> allorderBeen = JsonUtil.json2beans(items, AllorderBean.class);
                        allorderBeanList.clear();
                        allorderBeanList.addAll(allorderBeen);
                        if (allorderBeanList.size() > 0) {
                            allOrdeAdapter.updateList(allorderBeanList, true);
                        } else {
                            allOrdeAdapter.updateList(null, false);
                        }
                        allOrdeAdapter.notifyDataSetChanged();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onNoNetwork(String state) {
            }
        });
    }
}
